import { Component, OnInit } from '@angular/core';
import { CommonService } from '../../../../services/common.service';
import { ActivatedRoute } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';


@Component({
  selector: 'app-contractextractionmodeledit',
  templateUrl: './contractextractionmodeledit.component.html',
  styleUrls: ['./contractextractionmodeledit.component.css']
})
export class ContractextractionmodeleditComponent implements OnInit {
  customStyle = {
    background: '#F2F5FC',
    'border-radius': '4px',
    'margin-bottom': '24px',
    border: '1px solid #DFE1E6'
  }
  // 用户点击编辑跳转此页面,点击的当前行数据
  // 基本信息的数据
  modelData: any = {
    model_id: '',
    model_name: '',
    task_type: '',
    description: '',
    data_process_config: '',
    model_type: '',
    file_name: ''
  };

  // 标题检索模块数据
  // ModelTitleConfig:any=[]
  // 删除的模态框
  deleteShow = false;
  isAble: boolean = false;
  switchValue: boolean = true;
  // 标题检索模块数据
  titleList: any = [
    {
      is_reverse: true,
      search_pattern: []
    }
  ];
  // 标题检索模块 规则操作规范 
  stateTitle: boolean = true;
  // op工作流数据
  processConfig: any = [];
  // op工作流级联选择器
  // 父级
  provinceDatas: any = [
    {
      op: "文本匹配",
      type: "search"
    }, {
      op: "文本切割",
      type: "split"
    }, {
      op: "关键词检测",
      type: "filter"
    }
  ];
  // 儿子
  cityData: any = {
    search: [{
      op: "单模式匹配",
      type: "first-search"
    }, {
      op: "多模式匹配",
      type: "multi-search"
    }, {
      op: "移除前后缀",
      type: "remove-fix"
    }],
    split: [
      {
        op: "按段落切割",
        type: "paragraph"
      }, {
        op: "按句子切割",
        type: "sentence"
      }, {
        op: "按标点切割",
        type: "punctuation"
      }, {
        op: "按词汇切割",
        type: "word"
      }
    ],
    filter: [
      {
        op: "按关键词保留",
        type: "keep"
      }, {
        op: "按关键词删除",
        type: "remove"
      }
    ]
  };
  // op工作流禁用状态
  selectIsAble: boolean = false
  // 删除op  id
  deleteConfigId: any = null
  // 删除op index
  deleteConfigIndex: any = null
  noData: boolean = false;

  //轮询JobID
  jobTestId: string = "";
  //轮询定时器
  jobTimer: any = null;
  //当前选中的文件
  file: any = {};
  isCanUpload: boolean = false;
  uploadFileName: string = "";
  selectedModeType = 'Zhejiang';
  modeTypes = ['Zhejiang', 'Jiangsu'];

  queryJobTimer: any = null;

  textTest: string = "";
  reasoningTxt: string = ""; //推理结果

  constructor(public http: CommonService,
    private route: ActivatedRoute,
    private message: NzMessageService) { }
  ngOnInit(): void {
    // 接收上个页面传过来的模型id
    this.route.queryParams.subscribe(queryParams => {
      this.modelData.model_id = queryParams.model_id;
    });
    // 查询模型
    this.queryModel()
  }

  ngOnDestroy(): void {
    //Called once, before the instance is destroyed.
    //Add 'implements OnDestroy' to the class.
    if (this.queryJobTimer != null) {
      clearInterval(this.queryJobTimer)
    }
  }

  // 查询模型
  queryModel() {
    this.http.post('/contract-extraction/model-mgr/query-model', {
      model_id: this.modelData.model_id
    }).then((res: any) => {
      console.log(res)
      this.modelData.model_id = res.result.model_id
      this.modelData.file_name = res.result.file_name
      this.modelData.description = res.result.description
      this.modelData.model_name = res.result.model_name
      this.modelData.model_type = res.result.model_type
      this.selectedModeType = this.modelData.model_type
      this.modelData.task_type = res.result.task_type
      if (this.modelData.task_type == "实体识别") {
        this.modeTypes = ["lstm_crf", "bert"]
      } else if (this.modelData.task_type == "文本分类") { this.modeTypes = ["fasttext", "bert"] }
      this.modelData.update_time = res.result.update_time
      // 标题检索数据
      // 判断后台是否给返回了空的title数据
      if (Object.keys(res.result.title_config).length == 0) {
        // 如果返回的数据为空 就执行这个方法 向页面渲染一个空的title输入框
        let titleArr = {
          is_reverse: true,
          search_pattern: [
            { value: "" }
          ]
        }
        res.result.title_config = titleArr
        this.titleList = res.result.title_config
      } else {
        // 将标题的数据 解析成对象 
        let search_patternArr = []
        res.result.title_config.search_pattern.map(i => {
          console.log(i)
          let obj = {
            value: i
          }
          search_patternArr.push(obj)
        })
        res.result.title_config.search_pattern = search_patternArr
        this.titleList = res.result.title_config
        console.log(this.titleList)
      }

      // op工作流数据
      // 判断后台是否给返回了空的数据
      if (res.result.data_process_config.length == 0) {
        return
      } else {
        this.processConfig = res.result.data_process_config
        this.processConfig.forEach(e => {
          console.log(e.op_config)
          if (e.op_config) {
            e.op_config.isTrue = false
          }
        });
        console.log(this.processConfig)
      }
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }
  // 新增标题长度限制
  getlength(key) {
    switch (key) {
      case 1: return '一'
        break;
      case 2: return '二'
        break;
      case 3: return '三'
        break;
      case 4: return '四'
        break;
      case 5: return '五'
        break;
    }
  }
  // 编辑按钮
  editTitleConfig() {
    // 将编辑按钮隐藏 显示保存按钮
    this.stateTitle = false
  }
  // 4.6	更新模型的标题检索配置
  updateTitleConfig() {
    let search_patternArr = []
    let istrue = false;//判断是否value为空
    this.titleList.search_pattern.map(i => {
      i.value = i.value.replace(/^\s+|\s+$/g,"")
      if (i.value == '') {
        this.message.error('标题检索不能为空!')
        istrue = true
        return
      } else {
        search_patternArr.push(i.value)
      }
    })
    if (istrue == false) {
      this.http.post('/contract-extraction/model-mgr/update-title-config', {
        model_id: this.modelData.model_id,
        is_reverse: this.titleList.is_reverse,
        search_pattern: search_patternArr
      }).then((res: any) => {
        console.log(res)
        if (res && res.error_code && res.error_code == "AIS.0000") {
          this.message.success("保存成功！");
          this.stateTitle = true
        } else {
          this.message.error("保存失败，请稍后再试！");
        }
      }).catch((err: any) => {
        this.message.error(err.error_msg);
      })
    }
  }
  // 4.7	添加模型数据处理模块中OP
  addModel() {
    // 添加一条假数据
    this.processConfig.push({
      op_config: {
        op: "search",
        type: "first-search",
        pattern: '',
        isTrue: false
      }, op_id: ''
    });
  }
  // 父级选择器
  operationSelect(value, index) {
    this.processConfig[index].op_config.op = value
    // 操作选择器 对应类型
    if (value === 'search') {
      this.processConfig[index].op_config.type = 'first-search'
    } else if (value === 'split') {
      this.processConfig[index].op_config.type = 'paragraph'
    } else {
      this.processConfig[index].op_config.type = 'keep'
    }
  }
  // 子级选择器
  typeSelect(e) {
    // console.log(e)
  }
  // op工作流编辑按钮
  editConfig(index) {
    // this.selectIsAble = true
    console.log(index)
    this.processConfig[index].op_config.isTrue = true
  }
  // 4.8 更新模型数据处理模块中的OP 更新按钮
  updateConfig(id, index) {
    // 如果id为空 就走添加的接口 给他添加一个
    if (id == "") {
      if (this.processConfig[index].op_config.op === 'search') {
        this.http.post('/contract-extraction/model-mgr/add-operator', {
          model_id: this.modelData.model_id,
          op_config: {
            op: this.processConfig[index].op_config.op,
            type: this.processConfig[index].op_config.type,
            pattern: this.processConfig[index].op_config.pattern
          }
        }).then((res: any) => {
          console.log(res)
          if (res && res.result && res.result.op_id) {
            this.processConfig[index].op_id = res.result.op_id
            // 将选择器 转换成禁用状态
            this.processConfig[index].op_config.isTrue = false
            this.message.success("添加成功!")
          } else {
            this.message.error("添加失败!")
          }
        }).catch((err: any) => {
          this.message.error(err.error_msg);
        })
      } else if (this.processConfig[index].op_config.op === 'filter') {
        this.http.post('/contract-extraction/model-mgr/add-operator', {
          model_id: this.modelData.model_id,
          op_config: {
            op: this.processConfig[index].op_config.op,
            type: this.processConfig[index].op_config.type,
            keywords: this.processConfig[index].op_config.keywords
          }
        }).then((res: any) => {
          console.log(res)
          if (res && res.result && res.result.op_id) {
            this.processConfig[index].op_id = res.result.op_id
            // 将选择器 转换成禁用状态
            this.processConfig[index].op_config.isTrue = false
            this.message.success("添加成功!")
          } else {
            this.message.error("添加失败!")
          }
        }).catch((err: any) => {
          this.message.error(err.error_msg);
        })
      } else {
        this.http.post('/contract-extraction/model-mgr/add-operator', {
          model_id: this.modelData.model_id,
          op_config: {
            op: this.processConfig[index].op_config.op,
            type: this.processConfig[index].op_config.type,
          }
        }).then((res: any) => {
          console.log(res)
          if (res && res.result && res.result.op_id) {
            this.processConfig[index].op_id = res.result.op_id
            // 将选择器 转换成禁用状态
            this.processConfig[index].op_config.isTrue = false
            this.message.success("添加成功!")
          } else {
            this.message.error("添加失败!")
          }
        }).catch((err: any) => {
          this.message.error(err.error_msg);
        })
      }
    } else {
      // 如果opid不为空 就走更新接口
      if (this.processConfig[index].op_config.op === 'search') {
        this.http.post('/contract-extraction/model-mgr/update-operator', {
          op_id: id,
          op_config: {
            op: this.processConfig[index].op_config.op,
            type: this.processConfig[index].op_config.type,
            pattern: this.processConfig[index].op_config.pattern
          }
        }).then((res: any) => {
          console.log(res)
          if (res.error_code == 'AIS.0000') {
            // 将选择器 转换成禁用状态
            this.processConfig[index].op_config.isTrue = false
            this.message.success("更新成功!")
          } else {
            this.message.error("更新失败!")
          }
        }).catch((err: any) => {
          this.message.error(err.error_msg);
        })
      } else if (this.processConfig[index].op_config.op === 'filter') {
        this.http.post('/contract-extraction/model-mgr/update-operator', {
          op_id: id,
          op_config: {
            op: this.processConfig[index].op_config.op,
            type: this.processConfig[index].op_config.type,
            keywords: this.processConfig[index].op_config.keywords
          }
        }).then((res: any) => {
          console.log(res)
          if (res.error_code == 'AIS.0000') {
            // 将选择器 转换成禁用状态
            this.processConfig[index].op_config.isTrue = false
            this.message.success("更新成功!")
          } else {
            this.message.error("更新失败!")
          }
        }).catch((err: any) => {
          this.message.error(err.error_msg);
        })
      } else {
        this.http.post('/contract-extraction/model-mgr/update-operator', {
          op_id: id,
          op_config: {
            op: this.processConfig[index].op_config.op,
            type: this.processConfig[index].op_config.type
          }
        }).then((res: any) => {
          console.log(res)
          if (res.error_code == 'AIS.0000') {
            // 将选择器 转换成禁用状态
            this.processConfig[index].op_config.isTrue = false
            this.message.success("更新成功!")
          } else {
            this.message.error("更新失败!")
          }
        }).catch((err: any) => {
          this.message.error(err.error_msg);
        })
      }
    }
  }
  // 删除 op
  deleteConfig(id, index) {
    this.deleteShow = true;
    // 赋值拿到的 id 跟index
    this.deleteConfigId = id;
    this.deleteConfigIndex = index;
  }
  // 取消删除
  deleteshut() {
    this.deleteShow = false;
  }
  // 确认删除 4.8	删除模型数据处理模块中的操作
  deleteOk() {
    console.log(this.deleteConfigId)
    this.http.post('/contract-extraction/model-mgr/delete-operator', {
      op_id: this.deleteConfigId
    }).then((res: any) => {
      console.log(res)
      this.deleteShow = false;
      this.http.post('/contract-extraction/model-mgr/query-model', {
        model_id: this.modelData.model_id
      }).then((res: any) => {
        this.processConfig = res.result.data_process_config
        this.processConfig.forEach(e => {
          console.log(e.op_config)
          if (e.op_config) {
            e.op_config.isTrue = false
          }
        })
      }).catch((err: any) => {
        this.message.error(err.error_msg);
      })
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }
  // 4.9	导出模型训练数据（异步）
  exportTrain() {
    this.http.post('/contract-extraction/model-mgr/export-train-data', {
      model_id: this.modelData.model_id
    }).then((res: any) => {
      if (res.error_code == "AIS.0000") {
        this.jobTestId = res.result.job_id;
        this.getTestJob();
      } else {
        this.message.error("导出训练数据失败！");
      }
      console.log(res)
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }


  // job查询
  getTestJob() {
    let that = this;
    that.jobTimer = setInterval(function () {
      that.http.post('/contract-extraction/job-mgr/query-job', {
        job_id: that.jobTestId
      }).then((res: any) => {
        if (res.result) {
          if (res.result.job_status == "success") {
            that.downLoad(res.result.job_result.file_base64, res.result.job_result.file_name);
            if (that.jobTimer != null) {
              clearInterval(that.jobTimer)
            }
          } else if (res.result.job_status == "waiting") {
            that.message.info(that.jobTestId + "正在排队等待，请稍后！");
          } else if (res.result.job_status == "running") {
            that.message.info(that.jobTestId + "正在查询，请稍后！");
          } else {
            that.message.error(that.jobTestId + "查询失败，请重试！");
            if (that.jobTimer != null) {
              clearInterval(that.jobTimer)
            }
          }
        }
        else {
          that.message.error(that.jobTestId + "轮询查询失败，请重试！");
          if (that.jobTimer != null) {
            clearInterval(that.jobTimer)
          }
        }
      }).catch((data: any) => {
        that.message.error(that.jobTestId + data.error_msg);
        if (that.jobTimer != null) {
          clearInterval(that.jobTimer)
        }
      })
    }, 3000);
  }


  downLoad(fileBase64, fileName) {
    let base64Pdf = fileBase64;
    const arrayBuffer = this.dataURLtoBlob(base64Pdf); // 创建Array缓冲区
    this.createAndDownloadBlobFile(arrayBuffer, fileName);

  }

  //**dataURL to blob** 
  dataURLtoBlob(dataurl) {
    const binaryString = window.atob(dataurl); //如果不使用base64，则注释这个
    const bytes = new Uint8Array(binaryString.length);
    return bytes.map((byte, i) => binaryString.charCodeAt(i));
  }

  createAndDownloadBlobFile(body, filename) {
    const blob = new Blob([body]);
    const fileName = `${filename}`;
    if (navigator.msSaveBlob) {
      // IE 10+
      navigator.msSaveBlob(blob, fileName);
    } else {
      const link = document.createElement('a');
      //支持HTML5下载属性的浏览器
      if (link.download !== undefined) {
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', fileName);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    }
  }

  // 4.11	模型测试
  testModel() {
    if (this.textTest.length < 1) {
      this.message.error("请输入测试文本!");
      return;
    }

    this.http.post('/contract-extraction/model-mgr/test-model', {
      model_id: this.modelData.model_id,
      text: this.textTest
    }).then((res: any) => {
      console.log(res)
      if (res.error_code == "AIS.0000") {
        this.reasoningTxt = res.result;
        this.message.success("成功获取模型推理结果");
      } else {
        this.message.success("获取模型推理结果失败");
      }
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }
  //新增规则标题
  addTitle() {
    if (this.titleList.search_pattern.length < 5) {
      this.titleList.search_pattern.push({ value: "" })
    } else {
      this.message.error('标题检索最多可添加五级！')
    }
  }
  //编辑工作流
  editBpm() {
    this.isAble = true;
  }
  //删除规则标题
  deleteTitle(index: any) {
    if (this.stateTitle == true) {
      return this.message.error("请先选择编辑!")
    } else {
      this.titleList.search_pattern.splice(index, 1);
    }

  }
  //删除工作流
  deleteBpm() {

  }
  changeNodeta() {
    this.noData = true;
  }

  getFile(e) {
    let that = this;
    that.isCanUpload = false;
    let files = e.target.files[0];
    let fileName = files.name;
    var reader = new FileReader();
    reader.readAsDataURL(files);
    reader.onload = function () {
      that.file.file_name = fileName;
      let file64 = reader.result.toString();
      that.file.file_base64 = file64.substring(file64.indexOf(',') + 1);
      that.isCanUpload = true;
      that.uploadFileName = fileName;
    };
  }

  leadIn() {
    if (!(this.file && this.file.file_name)) {
      this.message.error("请选择上传文件！");
      return;
    }
    if (!this.isCanUpload) {
      this.message.error("文件尚未准备号好，请稍后！");
      return;
    }
    let that = this;
    this.http.post('/contract-extraction/model-mgr/import-model', {
      "model_id": that.modelData.model_id,
      "model_type": this.selectedModeType,
      file_name: that.file.file_name,
      file_data_base64: that.file.file_base64
    }).then((res: any) => {
      if (res.error_code == "AIS.0000") {
        that.file.job_id = res.result.job_id
        that.queryJob();
        that.message.success('测试文件成功，请等待测试结果！');
      }
    }).catch((err: any) => {
      that.message.error(err.error_msg)
    })
  }

  queryJob() {
    let that = this;
    this.queryJobTimer = setInterval(function () {
      var param = {
        job_id: that.file.job_id
      }
      that.http.post('/contract-extraction/job-mgr/query-job', param).then((res: any) => {
        if (res.error_code == "AIS.0000") {
          if (res.result.job_status == "success") {
            that.message.success("导入文件成功！");
            clearInterval(that.queryJobTimer);
          } else if (res.result.job_status == "fail" || res.result.job_status == "timeout") {
            that.message.success("导入文件失败！");
            clearInterval(that.queryJobTimer);
          }
        } else {
          that.message.error(res.error_msg); clearInterval(that.queryJobTimer);
        }
      }).catch((err: any) => {
        that.message.error(err.error_msg); clearInterval(that.queryJobTimer);
      });
    }, 3000)

  }

}
